<template>
	<div>
		<!--	基础信息-->
		<div class="df-base el-card">

			<el-card>
				<template #header>
					<div class="card-header">
						<span>造数场景信息</span>
					</div>
				</template>
				<el-row>
					<el-col :xs="15" :sm="15" :md="15" :lg="15" :xl="15" class="mb20">
						<div class="api-case__method" style="padding-left: 5px">
							<el-input
								size="default"
								v-model="state.form.url"
								placeholder="请输入完整请求路径"
								class="input-with-select"
							>
								<template #prepend>
									<el-select v-model="state.form.method"
														 size="default"
														 ref="methodRef"
														 placeholder=""
														 @change="methodChange"
														 style="width: 100px; color: #22a1c4">
										<el-option
											v-for="item in state.methodList"
											:key="item"
											:label="item"
											:value="item">
											<span :class="[`method-color-${item.toLowerCase()}`]">{{ item }}</span>
										</el-option>
									</el-select>
								</template>
							</el-input>
						</div>
					</el-col>
					<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
						<!--					<div class="api-case__operation" style="padding-left: 12px">-->
						<!--						<el-button size="default" type="primary" @click="saveOrUpdateOrDebug('save')" class="title-button">保存-->
						<!--						</el-button>-->
						<!--						&lt;!&ndash;		<el-button size="default" type="success" @click="handleDebug">调试</el-button>&ndash;&gt;-->
						<!--						&lt;!&ndash;    <el-button size="default" type="danger" @click="saveOrUpdateOrDebug('debug')">删除</el-button>&ndash;&gt;-->
						<!--					</div>-->
					</el-col>
					<!--      </div>-->
				</el-row>

				<div class="scene_detail">
					<el-form ref="formRef"
									 :model="state.form"
									 label-width="auto"
									 label-position="right"
									 :rules="state.rules">
						<el-row :gutter="24">
							<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
								<el-form-item label="场景名称" prop="name">
									<el-input v-model.trim="state.form.scene_name"
														style="width: 100%;"
														clearable
														placeholder="请输入场景名称"></el-input>
								</el-form-item>

							</el-col>

							<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">

								<el-form-item label="团队/组织" prop="project_id">
									<el-select
										v-model="state.form.team"
										size="small"
										ref="methodRef"
										placeholder=""
										@change="methodChange"
										style="width: 100px; color: #22a1c4">
										<el-option
											v-for="item in state.teams"
											:key="item"
											:label="item"
											:value="item">
											<span :class="[`method-color-${item.toLowerCase()}`]">{{ item }}</span>
										</el-option>
									</el-select>
									<!--								<el-cascader v-model="state.form.team"-->
									<!--														 :props="{label:'name', value:'id'}"-->
									<!--														 :options="state.projectTree"-->
									<!--														 filterable-->
									<!--														 style="width: 100%"-->
									<!--														 @change="projectModuleChange"/>-->
								</el-form-item>
							</el-col>

							<el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">

								<!--							<el-form-item label="接口标签" prop="tag">-->
								<!--								<el-tag-->
								<!--									v-for="tag in state.form.tags"-->
								<!--									:key="tag"-->
								<!--									size="default"-->
								<!--									type="success"-->
								<!--									closable-->
								<!--									style="{margin-left: 0.25rem;margin-right: 0.25rem;}"-->
								<!--									:disable-transitions="false"-->
								<!--									@close="removeTag(tag)"-->
								<!--								>{{ tag }}-->
								<!--								</el-tag>-->

								<!--								<el-input-->
								<!--									v-if="state.editTag"-->
								<!--									ref="caseTagInputRef"-->
								<!--									v-model="state.tagValue"-->
								<!--									class="ml-1 w-20"-->
								<!--									size="small"-->
								<!--									@keyup.enter="addTag"-->
								<!--									@blur="addTag"-->
								<!--									style="width: 100px"-->
								<!--								/>-->
								<!--								<el-button v-else size="small" @click="showEditTag">-->
								<!--									+ New Tag-->
								<!--								</el-button>-->
								<!--							</el-form-item>-->

							</el-col>

							<el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="描述" prop="">
									<el-input size="default"
														type="textarea"
														v-model.trim="state.form.remarks"
														style="width: 100%;"
														placeholder="请输入用例名称"></el-input>
								</el-form-item>
							</el-col>

							<el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">

							</el-col>

							<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
								<!--							<el-form-item label="创建用户" prop="">-->
								<!--								<strong>{{ state.form.created_by_name }}</strong>-->
								<!--							</el-form-item>-->
							</el-col>

							<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
								<!--							<el-form-item label="创建时间" prop="">-->
								<!--								<strong>{{ state.form.creation_date }}</strong>-->
								<!--							</el-form-item>-->
							</el-col>

							<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
								<!--							<el-form-item label="更新用户" prop="" style="width: 100%;">-->
								<!--								<strong>{{ state.form.updated_by_name }}</strong>-->
								<!--							</el-form-item>-->
							</el-col>

							<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
								<!--							<el-form-item label="更新时间" prop="" style="width: 100%;">-->
								<!--								<strong>{{ state.form.updation_date }}</strong>-->
								<!--							</el-form-item>-->
							</el-col>
						</el-row>
					</el-form>
				</div>
			</el-card>
		</div>
		<!--	参数-->
		<div class="df-params">
			<el-card>
				<template #header>
					<div class="card-header">
						<span>参数信息</span>
					</div>
				</template>
				<z-table
					:show-page="false"
					:columns="state.columns"
					:data="state.elementList"
					ref="tableRef"
					:border="false"
					v-model:page-size="state.listQuery.pageSize"
					v-model:page="state.listQuery.page"
					:total="state.total"
					@pagination-change="getElementList"
				>
				</z-table>

				<!--	底部按钮-->
				<div>
					<el-row>
						<el-col :span="24"><div class="grid-content ep-bg-purple-dark" />
							<div class="grid-content ep-bg-purple-dark">
								<el-button size="default" type="primary" @click="saveConfig()" class="title-button">提交
								</el-button>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-card>
		</div>
	</div>

</template>

<script setup name="DataFactoryConfig">
import {ElButton, ElInput, ElMessage, ElMessageBox, ElOption, ElSelect} from "element-plus";
import {h, reactive, watch} from "vue";
import {dfApi} from "/@/api/dataFactory/df";
import {RefreshLeft, Edit, CirclePlus} from "@element-plus/icons"

// 基础信息区域
const createForm = () => {
	return {
		env_id: null,
		id: null,
		method: 'POST',
		scene_name: '',
		url: '',
		ssl: false,
		code_id: null,
		code: '',
		team: '',
		project_id: null,
		module_id: null,
		tags: [],
		priority: 3,
		remarks: "",
	}
}

// 参数区域
const props = defineProps({
	pageId: {
		type: Number,
		default: 0
	}
})

const state = reactive({
	columns: [
		{label: '序号', columnType: 'index', width: 'auto', show: true},
		{
			key: 'key_name', label: '参数名', width: '', align: 'center', show: true,
			render: ({row}) => h(ElInput, {
				modelValue: row.key_name,
				placeholder: '请输入参数key',
				clearable: true,
			}),
		},
		{
			key: 'key_type', label: '参数类型', width: '', align: 'center', show: true,
			render: ({row}) => h(ElSelect, {
					style: 'width: 100%',
					modelValue: row.key_type,
					placeholder: '请选择参数类型',
					clearable: true,
				}, () => state.paramsTypes.map((type) => h(ElOption, {
					key: type.key,
					label: type.label,
					value: type.value
				}))
			),
			renderHeader: () => h('div', {}, [
				h('span', {
					style: 'margin-right: 10px'
				}, "参数类型"),
				// h(ElButton, {
				// 	type: "primary",
				// 	icon: Edit,
				// 	round: true,
				// }, () => "编辑"),
				// h(ElButton, {
				// 	type: "success",
				// 	icon: RefreshLeft,
				// 	round: true,
				// }, () => "刷新")
			])
		},
		// 定位值用不到，注释掉
		{
			key: 'input_type', label: '输入框类型', width: '', align: 'center', show: true,
			render: ({row}) => h(ElSelect, {
				modelValue: row.input_type,
				placeholder: '请选择输入框类型',
				clearable: true,
			},() => state.inputTypes.map((type) => h(ElOption, {
				key: type.key,
				label: type.label,
				value: type.value
			}))
			)
		},
		{
			key: 'remarks', label: '备注', width: '', align: 'center', show: true,
			render: ({row}) => h(ElInput, {
				modelValue: row.remarks,
				placeholder: '请输入备注',
				clearable: true,
			},)
		},
		{
			label: '操作', fixed: 'right', width: '140', align: 'center',
			render: ({row, $index}) => h("div", null, [
				h(ElButton, {
					type: "primary",
					onClick: () => {
						saveParams(row)
					}
				}, () => '保存'),

				h(ElButton, {
					type: "danger",
					onClick: () => {
						deletedElement(row, $index)
					}
				}, () => '删除')
			]),
			renderHeader: () => h('div', {}, [
				h(ElButton, {
					type: "success",
					icon: CirclePlus,
					round: true,
					onClick: () => {
						addParams()
					}
				}, () => "添加参数")
			])
		},
	],
	elementList: [],
	total: 0,
	loading: false,
	listQuery: {
		page: 1,
		pageSize: 10,
		page_id: null
	},
	// 参数类型
	paramsTypes: [
		{key:1, label: '数字', value: 'num'},
		{key:2,label: '列表', value: 'list'},
		{key:3,label: '字典', value: 'dict'},
		{key:4,label: '字符串', value: 'string'},
	],
	inputTypes:[
		{key:1, label: '输入框', value: 'input'},
		{key:2,label: '选择框', value: 'select'},
		{key:3,label: '文本框', value: 'text'},
	],

	// 基础信息区域
	// cat apiInfo info
	showCaseInfo: false,
	//tag
	editTag: false,
	tagValue: "",
	// form
	isShowDialog: false,
	handleType: '',   //apiInfo 调用类型， 保存，调试
	// 表单及校验
	form: createForm(),
	rules: {
		scene_name: [{required: true, message: '请输入用例名', trigger: 'blur'}],
		project_id: [{required: true, message: '请选择所属项目', trigger: 'blur'}],
		module_id: [{required: true, message: '请选择所属模块', trigger: 'blur'}],
	},
	// project
	teams: ['交易','直播','国际'],
	projectQuery: {
		page: 1,
		pageSize: 1000,
	},
	// module
	moduleList: [],
	moduleQuery: {
		page: 1,
		pageSize: 1000,
		project_id: null,
	},

	// url
	methodList: ['POST', "GET", "PUT", "DELETE"],

	// env
	showEnvPage: false,
	envList: []

});

const getElementList = () => {
	state.loading = true
	dfApi().getList(state.listQuery)
		.then((res) => {
			// state.elementList = res.data.rows;
			// state.total = res.data.rowTotal;
		})
		.finally(() => {
			state.loading = false
		})
};
// 防止警告，先加上方法，暂时没有用
const methodChange = () =>{

}
const addParams = () => {
	// unshift-头插入，改成尾差入 push
	state.elementList.push({
		key_name: '',
		key_type: '',
		input_type:'',
		remarks: '',
	})
}

// 保存配置
const saveConfig = ()=> {
	let base_info = state.form
	let params = state.elementList
	let data = {}
	data['base_info'] = base_info
	data['params'] = params
	console.log('开始保存配置')
	console.log(data)
	dfApi().saveOrUpdate(data)
		.then(res => {
			ElMessage.success('请求成功')
			console.log('保存配置')
		})
}


// 更新保存 元素
const saveParams = (row) => {
	console.log(state, "state")
	// 判断有 row.key_name 则保存，不然就是参数为空
	if (row.key_type && row.key_name) {
		// TODO 此处不该直接保存，应该在最后提交数据的时候统一保存

		dfApi().saveOrUpdate(row)
			.then(res => {
				row._edit = false
				ElMessage.success('保存成功')
				// 保存成功后不刷新页面，直接塞入id， 不然后面点删除数据id为空
				if (!row.id) {
					state.total++
				}
				row.id = res.data.id
			})
	} else {
		ElMessage.warning('元素，或者定位值不能为空!')
	}
}


// 删除
const deletedElement = (row, index) => {
	ElMessageBox.confirm('是否删除该条数据, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		if (!row.id) {
			state.elementList.splice(index, 1)
			return
		}
		// TODO 此处需要注释掉，仅删除list中的数据即可
		useUiElementApi().deleted({id: row.id})
			.then((res) => {
				ElMessage.success('删除成功')
				getElementList()
			})
	})
}

// z-tab此处不需要分页器，注释掉监听，不然会导致白页
// watch(
// 	() => props.pageId,
// 	(page_id) => {
// 		state.elementList = []
// 		if (page_id) {
// 			state.listQuery.page_id = props.pageId
// 			getElementList()
// 		}
// 	},
// 	{
// 		deep: true,
// 	}
// );

</script>

<style scoped lang="scss">


.df-base {
	margin: 20px 20px;
	padding: 15px 16px;
	background-color: #ffffff;
	border-radius: 10px;
	border-left: 5px solid #409eff;
	box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);

	.api-case__url_info {
		display: flex;
		margin-bottom: 20px;
	}

	:deep(.input-with-select .el-input-group__prepend) {
		background-color: var(--el-fill-color-blank);
	}
}
.df-params{
	margin-left: 20px;
	margin-top: 20px;
	margin-right: 20px;
}

.grid-content {
	display: flex; /* 设置为 Flex 容器 */
	justify-content: center; /* 水平居中 */
	align-items: center; /* 垂直居中 */
	height: 100px; /* 设置一个高度，确保垂直居中生效 */
}
.method-color-get {
	color: #61affe
}

.method-color-post {
	color: #49cc90
}

.method-color-delete {
	color: #f93e3d
}

.method-color-put {
	color: #fca130
}

.method-color-na {
	color: #f56c6c
}

</style>